/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import LigacaoBd.Teste_Acesso_BD;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
/**
*
* @author 
*/
@WebServlet(name = "Controlador", urlPatterns = {"/Controlador"})
public class Controlador extends HttpServlet {
    
    private String id;
    private String nome;
    private String apelido;
    private String bi;
    private String telemovel;
    private String email;
    private String dataNasc;
    private String username;
    private String password;
    public Boolean validacao=false;
    private boolean inserido;
    private String nomeComentario;
    private String emailComentario;
    private String comentario;
    private String s;
    private String opcFiltro;
    private HttpSession session;
    private Vector carros;
 
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {            
                
            //out.println("</body>");
            //out.println("</html>");
        } finally {           
            out.close();
        }
    }
 
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                
                
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                Enumeration paramNames = request.getParameterNames(); 
                session = request.getSession();
        
              
                    String paramName = (String)paramNames.nextElement();      
                    String[] paramValues = request.getParameterValues(paramName);
                    if (paramValues.length == 1) {
                        String paramValue = paramValues[0];
                    if (paramValue.length() == 0)
                        out.print("<I>No Value</I>");
                    }

                 if(request.getParameter("accao").equals("login")){                    
                    
                    username = request.getParameter("user");
                    password = request.getParameter("pass");
        
                    Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                    validacao=acessoBD.loginConfirm(username, password);
        
                    if(validacao==true){                                   
                        
                        session.setAttribute("user",username);
                        session.setAttribute("pass",password);
                        session.setAttribute("loginValido",true);   
                        response.sendRedirect("/Virtual_MStand/index.jsp");

                    }else{
                        
                        session.setAttribute("loginValido",null); 
                        response.sendRedirect("index.jsp");
                        
                    }
                    
                 }else if( request.getParameter("accao").equals("logout")){
                    
                    session.setAttribute("loginValido",null);
                    response.sendRedirect("index.jsp");
                    
                }else if( request.getParameter("accao").equals("index")){
                    response.sendRedirect("index.jsp");
                    
                }else if( request.getParameter("accao").equals("utilizador")){
                    if(validacao){
                        
                        Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                        id = acessoBD.userID(username).toString();
                        session.setAttribute("idUtilizador", id);
                        Vector dUtilizador = new Vector();
                        dUtilizador = acessoBD.userInfo(id);
                        session.setAttribute("nome", dUtilizador.elementAt(1).toString());
                        session.setAttribute("apelido", dUtilizador.elementAt(2).toString());
                        session.setAttribute("bi", dUtilizador.elementAt(3).toString());
                        session.setAttribute("telemovel", dUtilizador.elementAt(4).toString());
                        session.setAttribute("dataNasc", dUtilizador.elementAt(5).toString());
                        session.setAttribute("email", dUtilizador.elementAt(6).toString());
                        session.setAttribute("topologia", dUtilizador.elementAt(7).toString());
                        
                    }
                    response.sendRedirect("utilizador.jsp");
                    
                }else if( request.getParameter("accao").equals("procurar")){
                    
                    int nCarros = 0;
                    Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                    if(request.getParameter("filtro")!=null){
                        if(request.getParameter("filtro").equals("0")){
                                opcFiltro = "0";
                        }else if(request.getParameter("filtro").equals("1")){
                                opcFiltro = "1";
                        }else if(request.getParameter("filtro").equals("2")){
                                opcFiltro = "2";
                        }else if(request.getParameter("filtro").equals("3")){
                                opcFiltro = "3";
                        }else if(request.getParameter("filtro").equals("4")){
                                opcFiltro = "4";
                        }else if(request.getParameter("filtro").equals("5")){
                                opcFiltro = "5";
                        }
                    }else {
                        opcFiltro = "0";
                    }                    
                    carros = acessoBD.getCarros(Integer.parseInt(opcFiltro));
                    session.setAttribute("carros", carros);    
                    nCarros = carros.size()/11;
                    session.setAttribute("nCarros", nCarros);
                    response.sendRedirect("procurar.jsp");
                    
                }else if( request.getParameter("accao").equals("novidades")){
                    response.sendRedirect("novidades.jsp");
                    
                }else if( request.getParameter("accao").equals("novoAnuncio")){
                    response.sendRedirect("Novo_Anuncio.jsp");
                    
                }else if( request.getParameter("accao").equals("criar")){
                      Vector nUtilizador = new Vector();
                      String utilizadors ;
                     nome = request.getParameter("nome");
                     apelido = request.getParameter("apelido");
                     bi = request.getParameter("bi");
                     telemovel = request.getParameter("telemovel");
                     email = request.getParameter("email");
                     dataNasc = request.getParameter("dataNasc");
                     username = request.getParameter("user");
                     password = request.getParameter("pass");
                     
                     Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                     
                     nUtilizador = acessoBD.n_utilizadores();
                     utilizadors =  String.valueOf(nUtilizador.size()/8 +1) ;
                     
                     
                     
                     inserido=acessoBD.novo_registo(nome,apelido,bi,telemovel,email,dataNasc,utilizadors);
                     inserido = acessoBD.novo_registoLogin(username, password, utilizadors);
                     if(inserido){       
                          session.setAttribute("inserido",true);   
                          response.sendRedirect("estado_registo.jsp");
                          
                          
                                }
                     else if(!inserido){
                          session.setAttribute("inserido",null);   
                          response.sendRedirect("estado_registo.jsp");
                          
                     }
                
                } else if( request.getParameter("accao").equals("inserir_comentario")){
                        Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                        Vector  nComentarios = acessoBD.GetComentarios();
                        String  nComentario =  String.valueOf(nComentarios.size()/5 +1) ;
                        String carroComentario = String.valueOf(request.getSession().getAttribute("idCarroActual"));
                        comentario = request.getParameter("comment");
                        emailComentario = request.getParameter("email");
                        nomeComentario = request.getParameter("nome");
                        acessoBD.insereComentario(comentario, emailComentario, nomeComentario, carroComentario, nComentario);
                        response.sendRedirect("procurar.jsp");
                                   
                } else if( request.getParameter("accao").equals("licitarCarro")){
                        response.sendRedirect("licitarCarro.jsp");
                } else if( request.getParameter("accao").equals("novaLicitacao")){
                        int novoValor;
                        novoValor = Integer.parseInt( (String) request.getParameter("valorLicitar")); 
                        Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                        int valorActual = acessoBD.getPrecoActual(request.getSession().getAttribute("idCarroActual").toString());
                        if(novoValor> valorActual){
                            acessoBD.novaLicitacao(request.getSession().getAttribute("idCarroActual").toString(), (String) request.getParameter("valorLicitar"));
                            response.sendRedirect("licitacaoSucesso.jsp");
                        }else {
                            response.sendRedirect("licitacaoSemSucesso.jsp");
                        }
                        
                        
                }else if( request.getParameter("accao").equals("inserir_anuncio")){
                        Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                        id = acessoBD.userID(username).toString();
                        session.setAttribute("idUtilizador", id);
                        Vector  nCarros = acessoBD.getCarros();
                        String  nCarro =  String.valueOf(nCarros.size()/11 +1) ;
                        String fileinput = "C:\\Users\\joao\\Documents\\NetBeansProjects\\trunk\\Virtual MStand\\web\\Imagens\\" + request.getParameter("fileinput");
                        String fileoutput = "C:\\Users\\joao\\Documents\\NetBeansProjects\\trunk\\Virtual MStand\\web\\Imagens\\" + String.valueOf(nCarro)+ ".jpg";
                        this.renameFile(fileinput, fileoutput);
                        String marca = request.getParameter("marca");
                        String modelo = request.getParameter("modelo");
                        String ano = request.getParameter("ano");
                        String caracteristicas = request.getParameter("caracteristicas");
                        String precoBase = request.getParameter("precoBase");
                        String precoCompra = request.getParameter("precoCompra");
                        String combustivel = request.getParameter("combustivel");
                        String cilindrada = request.getParameter("cilindrada");
                        String fotos = "1";
                        String idUser = id;
                        acessoBD.insereCarro(String.valueOf(nCarro), marca,modelo, ano, caracteristicas,fotos, precoBase, precoCompra,idUser, combustivel,cilindrada);
                        response.sendRedirect("procurar.jsp");
                                   
                }
                    
                    int nCarros = 0;
                    
                    session.setAttribute("carros", carros);    
                    nCarros = carros.size()/11;
                    Vector carroActual = new Vector();
                    
                    for(int i = 1; i!= nCarros+1; i++){
                          s = "item" + i + "/" ;
                          if( request.getParameter("accao").equals(s)){
                                 request.getSession().setAttribute("idCarroActual", i);
                                 for(int j = (i*11)-11; j!=(i*11); j++){
                                     carroActual.add(carros.elementAt(j));
                                 }
                                 Teste_Acesso_BD acessoBD = new Teste_Acesso_BD();
                                 request.getSession().setAttribute("carroActual", carroActual);
                                 String id = request.getSession().getAttribute("idCarroActual").toString();
                                 Vector comentarios = acessoBD.getComentarios(id);
                                 if(comentarios!=null){
                                 request.getSession().setAttribute("comentariosCarroActual", comentarios);
                                 }else{
                                     request.getSession().setAttribute("comentariosCarroActual", null);
                                 }
                                 response.sendRedirect("carro.jsp");                               
                                                                 
                          }                        
                          
                          
                    }           
            }
    
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
 
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    public void renameFile(String file, String toFile) {

        File toBeRenamed = new File(file);

        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {

            System.out.println("File does not exist: " + file);
            return;
        }

        File newFile = new File(toFile);

        //Rename
        if (toBeRenamed.renameTo(newFile)) {
            System.out.println("File has been renamed.");
        } else {
            System.out.println("Error renmaing file");
        }


    }
        
}